#!/usr/bin/env python3
# encoding: utf-8
"""
@author: kevin
@contact: evil365@gmail.com
@project : flask
@file: posion.py
@time: 2020/8/5 11:19
@license: (C) Copyright 2019-2025, Corporation Limited.
@desc:
"""
from app.models.zf_model import clientposion, product
from .errorCode import PosionAllFound, PosionNotFound
from sqlalchemy import extract, func, desc
import math


class my_posion(clientposion):
    
    @classmethod
    def get_posion(cls, usn, page):
        num = 10
        page = int(page)
        if page == 1:
            skip = 0
        else:
            skip = (page - 1) * num
        _posion = cls.query.with_entities(cls.quantity, cls.rateSequence, cls.assetType, product.name).outerjoin(product).filter(cls.userSn == usn, cls.delete_time == None).order_by(cls.sn.desc()).limit(num).offset(skip).all()
        count = cls.get_posion_count(usn)
        pages = math.ceil(count / num)
        if _posion:
            posion_data = []
            for i in _posion:
                tmp = {'quantity': str(i[0]), 'rateSequence': str(i[1]), 'assetType': i[2], 'name': i[3]}
                posion_data.append(tmp)
            _posion = {'list': posion_data, 'total': count, 'page': pages}
        else:
            raise PosionNotFound
        return _posion

    @classmethod
    def get_quantity(cls, usn):
        quantity = cls.query.with_entities(func.sum(cls.quantity)).filter_by(userSn=usn, delete_time=None).scalar()
        if quantity is None:
            return 0
        return quantity

    @classmethod
    def get_posion_count(cls, usn):
        count = cls.query.filter_by(userSn=usn, delete_time=None).count()
        if count is None:
            return 0
        return count
